package net.kunyv.util;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.FileWriter;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;















public class XMLUtil
{
    public static void addAttributes(Element element, HashMap attributeMap) {
        Set entrySet = attributeMap.entrySet();
        for (Iterator<Map.Entry> it = entrySet.iterator(); it.hasNext(); ) {
            Map.Entry entry = it.next();
            element.addAttribute(entry.getKey().toString(), entry.getValue()
                    .toString());
        }
    }









    public static Document readXML(InputStream is) {
        SAXReader reader = new SAXReader();
        Document document = null;
        try {
            document = reader.read(is);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return document;
    }











    public static boolean createXmlFile(Document document, String fileName) {
        try {
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("GBK");
            XMLWriter writer = new XMLWriter(new FileWriter(fileName), format);
            writer.write(document);
            writer.close();
            return true;
        }
        catch (Exception ex) {
            ex.printStackTrace();


            return false;
        }
    }









    public static Attribute getAttribute(Element element, String attributeName) {
        Attribute attribute = element.attribute(attributeName);
        if (null != attribute) {
            return attribute;
        }
        return null;
    }










    public static Element getChildElement(Element element, String elementName) {
        Element childelement = element.element(elementName);
        if (null != childelement) {
            return childelement;
        }
        return null;
    }
}
